package alf.mapping.service.maps;

/** motor de "mapas"
responsable de la logica del mapa (no de graficos).
por "arriba" debe haber un mapeo de elementos de mapa
a elementos graficos.
*/
import alf.common.data.DataException;
import alf.common.domain.AbstractDomainService;
import alf.common.domain.DomainException;
import alf.mapping.data.SimpleLoader;
import alf.mapping.data.SimpleSaver;
import alf.mapping.dto.maps.Item;
import alf.mapping.dto.maps.MapModel;
import alf.mapping.dto.maps.NavigationLink;
import alf.mapping.dto.maps.Room;
import alf.mapping.view.Env;
import android.graphics.Rect;

public class MapService extends AbstractDomainService {

	private SimpleLoader loader = new SimpleLoader();
	private SimpleSaver saver = null;

	public NavigationLink parseLink(String newLink,MapModel map) {
		NavigationLink link = null;
		String diagramPart, itemPart;
		if (newLink==null || newLink.equals("") || newLink.equals("/") || map==null) {
			return null;
		}
		if (newLink.contains("/")){
			int pos = newLink.indexOf("/");
			diagramPart = newLink.substring(0,pos);
			itemPart = newLink.substring(pos+1);
		} else {
			diagramPart = newLink;
			itemPart= null;
		}
		Env.debug("link:"+diagramPart+"+"+itemPart);
		for (Room r: map.getRooms()){
			if (r.getName().equals(diagramPart)){
				link = new NavigationLink();
				link.setDiagram(r);
				if (itemPart!=null){
					for (Item i: r.getEntidades()){
						if (itemPart.equals(i.getName())){
							link.setItem(i);
							return link;
						}
					}
				}
				return link;
			}
		}
		return null;
	}	
	
	public MapModel load(String path) throws DomainException {
		try {
			return loader.getModel(path);
		} catch (DataException e) {
			encapulate("Data error."+e.getMessage(),e);
		}
		return null;
	}
	
	public String save(MapModel m,String path) throws DomainException {
		if (saver==null) {
			saver = new SimpleSaver();
		}
		try {
			saver.save(m, path);
		} catch (DataException e) {
			encapulate("Data error."+e.getMessage(),e);
		}
		return null;
	}
	
	public Item newItem(String name,String type,Rect rect){
		Item e = new Item();
		e.setName(name);
		e.setType(type);
		e.setRect(rect);
		return e;
	}
}
